package com.qwc.blog.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qwc.blog.common.exception.BadRequestException;
import com.qwc.blog.entity.Category;
import com.qwc.blog.mapper.CategoryMapper;
import com.qwc.blog.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.qwc.blog.common.constant.CommonConstant.*;
import static com.qwc.blog.common.constant.ResponseConstant.*;

/**
 * <p>
 * 文章分类表 服务实现类
 * </p>
 *
 * @author qwc
 * @since 2021-10-29
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public List<Category> selectCategoryList(String name, String status) {
        return baseMapper.selectList(Wrappers.<Category>lambdaQuery()
                .eq(StringUtils.isNotBlank(name), Category::getName, name)
                .eq(StringUtils.isNotBlank(status), Category::getStatus, status)
                .orderByAsc(Arrays.asList(Category::getPid, Category::getSort)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCategory(Category category, String username) {
        checkSameName(category);
        category.setCreateBy(username);
        category.setUpdateBy(username);
        baseMapper.insert(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCategory(Category category, String username) {
        checkSameName(category);
        if (category.getCategoryId().equals(category.getPid())) {
            throw new BadRequestException(PID_WRONG);
        }
        category.setUpdateBy(username);
        baseMapper.updateById(category);
    }

    @Override
    public void deleteById(Integer categoryId) {
        List<Integer> list = new ArrayList<>();
        list.add(categoryId);
        addSonId(categoryId, list);
        int i = baseMapper.deleteBatchIds(list);
        log.info("删除了{}条分类", i);
    }

    @Override
    public Object selectMainCategoryList() {
        return baseMapper.selectList(Wrappers.<Category>lambdaQuery()
                .eq(Category::getPid, TOP_PARENT.intValue()).eq(Category::getStatus, YES));
    }

    private void addSonId(Integer categoryId, List<Integer> list) {
        List<Category> categories = baseMapper.selectList(Wrappers.<Category>lambdaQuery().eq(Category::getPid, categoryId));
        if (!categories.isEmpty()) {
            List<Integer> collect = categories.stream().map(Category::getCategoryId).collect(Collectors.toList());
            list.addAll(collect);
            for (Integer integer : collect) {
                addSonId(integer, list);
            }
        }
    }

    private void checkSameName(Category category) {
        List<Category> categories = baseMapper.selectList(Wrappers.<Category>lambdaQuery().eq(Category::getName, category.getName()));
        if (CollUtil.isNotEmpty(categories) && categories.stream().noneMatch(cate -> cate.getCategoryId().equals(category.getCategoryId()))) {
            throw new BadRequestException(USED_NAME);
        }
    }
}
